package com.gongpingjialoan.receiver;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;

import com.gongpingjialoan.global.GPJApplication;
import com.gongpingjialoan.utility.FileDownloadManager;

/**
 * Created by Administrator on 2016/10/14.
 */
public class DownloadReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        DownloadManager manager = (DownloadManager)context.getSystemService(Context.DOWNLOAD_SERVICE);
        if(DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(intent.getAction())){
            try {
                FileDownloadManager.getInstance(context).getDialog().dismiss();
            } catch (Exception e) {

            }
            DownloadManager.Query query = new DownloadManager.Query();
            //在广播中取出下载任务的id
            long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
            query.setFilterById(id);
            Cursor c = manager.query(query);
            if(c.moveToFirst()) {
                //获取文件下载路径
                String filename = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
                //如果文件名不为空，说明已经存在了，拿到文件名想干嘛都好
                if(filename != null) {
                    Intent i = new Intent(Intent.ACTION_VIEW);
                    Uri uri = Uri.parse("file://" + filename);
                    i.setDataAndType(uri, "application/vnd.android.package-archive");
                    //在服务中开启activity必须设置flag,后面解释
                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    GPJApplication.getInstance().startActivity(i);
                }
            }
        }


    }
}
